package com.xukktest.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.hadoop.hbase.HbaseTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class HBaseUtil {
    @Autowired
    private HbaseTemplate hbaseTemplate;
    private volatile Connection connection;

    public Connection getConnection() {
        if (null == this.connection) {
            synchronized (this) {
                if (null == this.connection) {
                    try {
                        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(200, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
                        // init pool
                        poolExecutor.prestartCoreThread();
                        this.connection = ConnectionFactory.createConnection(hbaseTemplate.getConfiguration(), poolExecutor);
                    } catch (IOException e) {
                        log.error("hbase connection资源池创建失败");
                    }
                }
            }
        }
        return this.connection;
    }

    public void createTable(String table, List<String> cols) {
        try {
            TableName tableName = TableName.valueOf(table);
            if (getConnection().getAdmin().tableExists(tableName)) {
                log.warn("表{}已存在", table);
            } else {
                HTableDescriptor hTableDescriptor = new HTableDescriptor(tableName);
                if (cols != null) {
                    for (String col : cols) {
                        HColumnDescriptor hColumnDescriptor = new HColumnDescriptor(col);
                        hTableDescriptor.addFamily(hColumnDescriptor);
                    }
                }
                getConnection().getAdmin().createTable(hTableDescriptor);
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

    }

    //删除表
    public void deleteTable(String table) {
        try {
            TableName tablename = TableName.valueOf(table);
            getConnection().getAdmin().disableTable(tablename);
            getConnection().getAdmin().deleteTable(tablename);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }
}
